package com.emergency.examine.service.impl;

import com.emergency.common.util.CommonUtils;
import com.emergency.common.util.IdWorker;
import com.emergency.examine.dao.*;
import com.emergency.examine.domain.*;
import com.emergency.examine.service.QuestionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class QuestionServiceImpl implements QuestionService {
    private final static Logger logger = LoggerFactory.getLogger(PaperServiceImpl.class);

    @Autowired
    private QuestionDao questionDao;

    @Autowired
    private OptionDao optionDao;

    @Autowired
    private AnswerDao answerDao;

    @Autowired
    private IdWorker idWorker;

    //添加题目信息
    @Override
    public String save(Question question) {
        if (CommonUtils.isNullOrEmpty(question.getId())) {
            question.setId(idWorker.nextId());
            question.setCreateTime(new Date());
        }
        //保存题目信息
        questionDao.save(question);
        optionSave(question);
        answerSave(question);
        return question.getId().toString();
    }

    //保存选项信息
    private void optionSave(Question question) {
        List<Option> options = question.getOption();
        if (!CommonUtils.isNullOrEmpty(options)) {
            options.forEach(option -> {
                option.setId(idWorker.nextId());
                option.setCreateTime(new Date());
                option.setQuestion(question);
            });
        }
        optionDao.saveAll(options);
    }

    //保存答案信息
    private void answerSave(Question question) {
        Answer answer = question.getAnswer();
        if (!CommonUtils.isNullOrEmpty(answer)) {
            answer.setId(idWorker.nextId());
            answer.setCreateTime(new Date());
            answer.setQuestion(question);
        }
        answerDao.save(answer);
    }


    //获取题目信息
    @Override
    public Question getInfo(Long questionId) {
        Question question = questionDao.findById(questionId).orElse(null);
        if (CommonUtils.isNullOrEmpty(question)) {
            logger.info("没有题目信息");
            return question;
        }
        //获取选项
        question.setOption(optionDao.findAllByQuestion(questionId));

        //获取答案
        question.setAnswer(answerDao.findByQuestionId(questionId));

        return question;
    }

    //删除题目信息
    @Override
    public void del(Long questionId) {
        answerDao.deleteByQuestionId(questionId);
        optionDao.deleteByQuestionId(questionId);
        questionDao.deleteById(questionId);
    }

    //查询
    @Override
    public Page<Question> findList(Map searchMap, int page, int size) {
        Specification<Question> specification = createSpecification(searchMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return questionDao.findAll(specification, pageRequest);
    }

    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<Question> createSpecification(Map searchMap) {

        return new Specification<Question>() {

            @Override
            public Predicate toPredicate(Root<Question> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();

                // 标题
                if (searchMap.get("title") != null && !"".equals(searchMap.get("title"))) {
                    predicateList.add(cb.like(root.get("title").as(String.class), "%" + (String) searchMap.get("title") + "%"));
                }
                // 类型
                if (searchMap.get("type") != null && !"".equals(searchMap.get("type"))) {
                    predicateList.add(cb.like(root.get("type").as(String.class), "%" + (String) searchMap.get("type") + "%"));
                }
                // 难度
                if (searchMap.get("diff") != null && !"".equals(searchMap.get("diff"))) {
                    predicateList.add(cb.like(root.get("diff").as(String.class), "%" + (String) searchMap.get("diff") + "%"));
                }
                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));

            }
        };

    }
}
